<template>
  <div class="home-page">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="container">
        <div class="nav-brand">
          <h1>长隆酒店预订</h1>
        </div>
        <nav class="nav-menu">
          <a class="nav-link active" @click.prevent="goHotels">酒店列表</a>
          <a v-if="isLoggedIn" class="nav-link" @click.prevent="goOrders">我的订单</a>
          <a v-if="isLoggedIn" class="nav-link" @click.prevent="goProfile">个人中心</a>
          <a v-if="!isLoggedIn" class="nav-link" @click.prevent="goLogin">登录</a>
          <span v-if="isLoggedIn" class="nav-link" style="cursor: default;">{{ displayName }}</span>
          <a v-if="isLoggedIn" class="nav-link" @click.prevent="logout">登出</a>
          <a class="nav-link ai-link" @click.prevent="openAi">问AI</a>
        </nav>
      </div>
    </header>

    <!-- 主要内容区域 -->
    <main class="main-content">
      <div class="container">
        <!-- 搜索区域 -->
        <div class="search-section">
          <h2>发现心仪酒店，长隆旗下</h2>
          <p class="search-desc">直接预订心仪酒店</p>
          <div class="search-bar">
            <a-input-search
              v-model:value="searchKeyword"
              placeholder="搜索酒店名称"
              enter-button="搜索"
              size="large"
              @search="handleSearch"
            />
          </div>
        </div>

        <!-- 酒店列表 -->
        <div class="hotels-section">
          <div class="section-header">
            <h3>热门酒店</h3>
            <div class="filter-options">
              <a-select v-model:value="starFilter" placeholder="星级筛选" style="width: 120px" @change="handleFilter">
                <a-select-option value="">全部</a-select-option>
                <a-select-option value="5">五星级</a-select-option>
                <a-select-option value="4">四星级</a-select-option>
                <a-select-option value="3">三星级</a-select-option>
              </a-select>
            </div>
          </div>

          <div class="hotels-grid" v-if="!loading">
            <div class="hotel-card" v-for="hotel in filteredHotels" :key="hotel.id" @click="goToDetail(hotel.id)">
              <div class="hotel-image">
                <img :src="hotel.imageUrl || fallbackImg(hotel.id)" :alt="hotel.name" />
                <div class="hotel-star">⭐ {{ hotel.star || 3 }}</div>
              </div>
              <div class="hotel-info">
                <h4 class="hotel-name">{{ hotel.name }}</h4>
                <p class="hotel-address">{{ hotel.address }}</p>
                <p class="hotel-desc">{{ hotel.description || '欢迎入住，舒适之选' }}</p>
                <div class="hotel-meta">
                  <span class="hotel-price">￥{{ hotel.priceAvg }}/晚起</span>
                  <span class="hotel-tel" v-if="hotel.tel">📞 {{ hotel.tel }}</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 加载状态 -->
          <div v-if="loading" class="loading-container">
            <a-spin size="large" />
            <p>正在加载酒店信息...</p>
          </div>

          <!-- 空状态 -->
          <div v-if="!loading && filteredHotels.length === 0" class="empty-container">
            <a-empty description="暂无酒店信息" />
          </div>
        </div>
      </div>
    </main>

    <!-- 页脚 -->
    <footer class="footer">
      <div class="container">
        <p>&copy; 2024 酒店预订系统. 保留所有权利.</p>
      </div>
    </footer>

    <!-- AI 聊天抽屉 -->
    <a-drawer :open="aiOpen" :title="null" placement="right" width="360" @close="closeAi">
      <template #title>
        <span class="ai-drawer-title">通义智能助手</span>
      </template>
      <div style="display:flex; flex-direction: column; height: 100%;">
        <div style="flex:1; overflow: auto; border:1px solid #f0f0f0; padding:8px; border-radius:4px;">
          <div v-for="(m, idx) in aiMessages" :key="idx" style="margin-bottom:8px;">
            <div style="font-weight:600; color:#555;">{{ m.role === 'user' ? '我' : '长隆小助手' }}</div>
            <div style="white-space: pre-wrap;">{{ m.content }}</div>
          </div>
          <div v-if="aiMessages.length===0" style="color:#999;">请提问：房间库存、酒店地址、入住时间等</div>
        </div>
        <div style="margin-top:8px; display:flex; gap:8px;">
          <a-input v-model:value="aiInput" placeholder="请输入您的问题..." @pressEnter="sendAi" />
          <a-button type="primary" :loading="aiLoading" @click="sendAi">发送</a-button>
        </div>
      </div>
    </a-drawer>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { hotelAPI } from '@/api/hotel'
import { aiAPI } from '@/api/ai'

const router = useRouter()
const isLoggedIn = ref(false)
const displayName = ref('')
const aiOpen = ref(false)
const aiInput = ref('')
const aiLoading = ref(false)
const aiMessages = ref([])

// 响应式数据
const hotels = ref([])
const loading = ref(false)
const searchKeyword = ref('')
const starFilter = ref('')

// 计算属性 - 过滤后的酒店列表
const filteredHotels = computed(() => {
  let result = hotels.value

  // 按关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(hotel => 
      hotel.name.toLowerCase().includes(keyword) ||
      hotel.address.toLowerCase().includes(keyword) ||
      (hotel.description && hotel.description.toLowerCase().includes(keyword))
    )
  }

  // 按星级筛选
  if (starFilter.value) {
    result = result.filter(hotel => hotel.star == starFilter.value)
  }

  return result
})

// 加载酒店数据
const loadHotels = async () => {
  loading.value = true
  try {
    const res = await hotelAPI.list(1, 50)
    const payload = res.data?.data || res.data || {}
    const list = Array.isArray(payload) ? payload : (payload.list || [])
    hotels.value = list.map(x => ({
      id: x.id,
      name: x.name,
      address: x.address,
      tel: x.tel,
      star: x.star,
      priceAvg: x.priceAvg || x.price_avg,
      imageUrl: x.imageUrl || x.image_url,
      description: x.description
    }))
  } catch (error) {
    console.error('加载酒店数据失败:', error)
    // 可以显示错误提示
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = (value) => {
  searchKeyword.value = value
}

// 筛选处理
const handleFilter = () => {
  // 筛选逻辑已在计算属性中处理
}

// 跳转到酒店详情
const goToDetail = (hotelId) => {
  router.push(`/fouter/hotels/${hotelId}`)
}

const syncAuth = () => {
  const token = localStorage.getItem('token')
  const user = JSON.parse(localStorage.getItem('userInfo') || '{}')
  isLoggedIn.value = !!token
  displayName.value = user?.realName || user?.username || ''
}

const goHotels = () => router.push('/fouter/hotels')
const goOrders = () => router.push('/fouter/orders')
const goProfile = () => router.push('/fouter/profile')
const goLogin = () => router.push('/login')
const logout = () => {
  localStorage.removeItem('token')
  localStorage.removeItem('userPermissions')
  localStorage.removeItem('userInfo')
  syncAuth()
  router.push('/login')
}

const openAi = () => {
  aiOpen.value = true
  if (aiMessages.value.length === 0) {
    aiMessages.value.push({ role: 'assistant', content: '您好，请问我能帮助您什么？' })
  }
}
const closeAi = () => { aiOpen.value = false }
const sendAi = async () => {
  if (!aiInput.value) return
  aiMessages.value.push({ role: 'user', content: aiInput.value })
  const prompt = `你只能回答以下范围内的问题：\n1) 酒店房间与价格、库存信息\n2) 数据库已有酒店的地址\n3) 入住时间（统一回答：当天14:00后可入住）\n除此之外一律回答“抱歉，我无法回答该问题。”\n\n用户问题：` + aiInput.value
  aiLoading.value = true
  try {
    const res = await aiAPI.ask(prompt)
    const reply = res.data?.reply || res.data?.data?.reply || '（无回复）'
    aiMessages.value.push({ role: 'assistant', content: reply })
  } catch (e) {
    aiMessages.value.push({ role: 'assistant', content: '抱歉，服务繁忙，请稍后再试。' })
  } finally {
    aiInput.value = ''
    aiLoading.value = false
  }
}

// 默认图片
const fallbackImg = (id) => `https://picsum.photos/seed/hotel-${id}/600/360`

// 组件挂载时加载数据
onMounted(() => {
  loadHotels()
  syncAuth()
})
</script>

<style scoped>
.home-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 顶部导航栏 */
.header {
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
}

.header .container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 64px;
}

.nav-brand h1 {
  margin: 0;
  color: #1890ff;
  font-size: 24px;
  font-weight: 600;
}

.nav-menu {
  display: flex;
  gap: 24px;
}

.nav-link {
  text-decoration: none;
  color: #666;
  font-weight: 500;
  padding: 8px 16px;
  border-radius: 4px;
  transition: all 0.3s;
}

.nav-link:hover,
.nav-link.active {
  color: #1890ff;
  background: #f0f8ff;
}

.ai-link {
  border: 1px solid #1890ff;
  color: #1890ff;
}

.ai-drawer-title { color: #722ed1; }

/* 主要内容 */
.main-content {
  flex: 1;
  padding: 40px 0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

/* 搜索区域 */
.search-section {
  text-align: center;
  margin-bottom: 40px;
}

.search-section h2 {
  font-size: 32px;
  color: #333;
  margin-bottom: 8px;
}

.search-desc {
  color: #666;
  font-size: 16px;
  margin-bottom: 24px;
}

.search-bar {
  max-width: 600px;
  margin: 0 auto;
}

/* 酒店列表区域 */
.hotels-section {
  margin-bottom: 40px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.section-header h3 {
  font-size: 24px;
  color: #333;
  margin: 0;
}

.filter-options {
  display: flex;
  gap: 12px;
}

/* 酒店网格 */
.hotels-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 24px;
}

.hotel-card {
  background: #fff;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
  cursor: pointer;
}

.hotel-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.hotel-image {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.hotel-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.hotel-star {
  position: absolute;
  top: 12px;
  right: 12px;
  background: rgba(0, 0, 0, 0.7);
  color: #fff;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 600;
}

.hotel-info {
  padding: 20px;
}

.hotel-name {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0 0 8px 0;
}

.hotel-address {
  color: #666;
  font-size: 14px;
  margin: 0 0 8px 0;
}

.hotel-desc {
  color: #999;
  font-size: 13px;
  line-height: 1.4;
  margin: 0 0 12px 0;
  height: 36px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.hotel-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.hotel-price {
  color: #e53935;
  font-size: 16px;
  font-weight: 600;
}

.hotel-tel {
  color: #666;
  font-size: 12px;
}

/* 加载和空状态 */
.loading-container,
.empty-container {
  text-align: center;
  padding: 60px 0;
}

.loading-container p {
  margin-top: 16px;
  color: #666;
}

/* 页脚 */
.footer {
  background: #f5f5f5;
  padding: 20px 0;
  text-align: center;
  color: #666;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header .container {
    flex-direction: column;
    height: auto;
    padding: 16px 20px;
  }

  .nav-menu {
    margin-top: 16px;
    flex-wrap: wrap;
    justify-content: center;
  }

  .search-section h2 {
    font-size: 24px;
  }

  .hotels-grid {
    grid-template-columns: 1fr;
  }

  .section-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
}
</style>
